package com.itheima.service;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.dto.RoleDTO;
import com.itheima.dto.UserDTO;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.*;

/**
 * @Author: bowen
 * @Date: 2019/7/22 15:11
 * @Description:
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {

	@Autowired
	UserDao userDao;

	@Autowired
	RoleDao roleDao;

	@Autowired
	PermissionDao permissionDao;

	/**
	 *  @描述：根据用户名获取用户信息
	 */
	public UserDTO findByUsername(String username) {
		UserDTO userDto = new UserDTO();
		User user= userDao.selectOne(User.builder().username(username).build());
         if(ObjectUtils.isEmpty(user)){
         	return null;
         }
		// 根据用户id查询角色信息
		BeanUtils.copyProperties(user, userDto);
		Set<Role> roleList= roleDao.findRolesByUserId(user.getId());
		Set<RoleDTO> roleDTOList= new HashSet<>();
         if(!CollectionUtils.isEmpty(roleList)){
         //	如果角色列表不为空，根据角色id查询权限信息
	       roleList.forEach(role->{
		       RoleDTO roleDTO = new RoleDTO();
		       BeanUtils.copyProperties(role, roleDTO);
		       Set<Permission> permissionList = permissionDao.findByRoleId(role.getId());
		      roleDTO.setPermissions(permissionList);
		       roleDTOList.add(roleDTO);
	       });
	         userDto.setRoles(roleDTOList);
         }
		return userDto;
	}

	/**
	 * 根据用户名得到菜单
	 * @param username
	 * @return
	 */
	@Override
	public List<Menu> findMenuByUsername(String username) {
		List<Menu> list = new ArrayList<>();
		//查询一级菜单
		list = userDao.findFirstMenuByUsername(username);
		//遍历一级菜单，根据用户名的带对应的二级菜单
		for (Menu menu : list) {
			List<Menu> secondMenu = userDao.findSecondMenuByUsernameAndFirst(username,menu.getId());
			menu.setChildren(secondMenu);
		}
		return list;
	}
}
